﻿#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author  : hu_cl
# @Contact : 760730895@qq.com 
# @Date    : 2020/7/27 15:52
# @File    : oracle_backups.py.py
import os
import paramiko
import time


class BackupOracle(object):
    def __init__(self, host, port, username, password, paths, db_name):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.paths = paths
        self.oracle_file_name = "oracle_backup_{}_{}.dmp".format(db_name, time.strftime("%Y%m%d"))  # 定义oracle文件名
        self.ssh_client = paramiko.SSHClient()
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh_client.connect(hostname=host, username=username, password=password, port=port)

    def backup_cmd(self, bk_ssh_client, db_username, db_password, db_name):
        # 远程备份数据库
        channel = bk_ssh_client.invoke_shell()
        time.sleep(0.5)
        channel.send("su - oracle \n")
        buff = ''
        while not buff.endswith('$ '):
            resp = channel.recv(9999)
            buff += resp.decode('utf-8')
    
        command = 'exp {}/{} file={}/{} owner={}'.format(db_username, db_password, self.paths,
                                                         self.oracle_file_name, db_name)
        channel.send(command)
        channel.send('\n')
        buff = ''
        while not buff.endswith('$ '):
            resp = channel.recv(999999999)
            buff += resp.decode('utf-8')
        # print(buff)

    def zip_files(self, zip_ssh_client):
        # 压缩服务器上的目标文件
        zip_commands = ('cd {}'.format(self.paths), 'zip -r {}.zip {}'.format(self.oracle_file_name,self.oracle_file_name))
        # cd /tmp, zip -r oracle_backup20200727.dmp.zip oracle_backup20200727.dmp
        zip_stdin, zip_stdout, zip_stderr = zip_ssh_client.exec_command(' \n '.join(zip_commands))
        res, err = zip_stdout.read(), zip_stderr.read()
        if err:
            print('执行压缩%s文件有信息返回为%s' % (self.oracle_file_name, err.decode()))
        else:
            print('压缩%s文件成功' % self.oracle_file_name)

    def download(self, dl_ssh_client, local_path):
        # 将数据库备份文件下载到本地服务器
        ftp_client = dl_ssh_client.open_sftp()
        print('正在下载%s.zip，请等待' % self.oracle_file_name)
        if not os.path.exists(local_path):
            os.makedirs(local_path)
        try:
            ftp_client.get('{}/{}.zip'.format(self.paths, self.oracle_file_name),
                           r'{}/{}.zip'.format(local_path, self.oracle_file_name))
        except Exception as exp:
            print('下载oracle数据库备份文件失败，返回码%s' % exp)
        else:
            print('下载oracle数据库备份文件成功')
        ftp_client.close()

    def remove_file(self, oracle_ssh_client):
        # 删除服务器上 生成的压缩文件
        commands = ('cd {}'.format(self.paths),
                    'rm -f {}/{}'.format(self.paths, self.oracle_file_name),
                    'rm -f {}/{}.zip'.format(self.paths, self.oracle_file_name))
        oracle_stdin, oracle_stdout, oracle_stderr = oracle_ssh_client.exec_command(' \n '.join(commands))
        res, err = oracle_stdout.read(), oracle_stderr.read()
        if err:
            print('删除文件失败,错误信息为%s' % err.decode())
        else:
            print('删除文件成功')

